package blog

import (
	"Blog/database"
	"Blog/model"
	sql2 "database/sql"
	"fmt"
	"github.com/kataras/iris/v12"
	"strconv"
)

func List(ctx iris.Context) {
	ctx.ViewData("Config", model.Configs)
	menuid := "0"
	sql := "SELECT `id`,`menu_id`,`title`,`desc`,`img`,`create_time`,`hits` FROM amibk_article"
	//ORDER BY create_time DESC LIMIT 0,6
	line := article{}
	var articles []article

	if ctx.URLParamExists("menuid") {
		sql = sql + " WHERE `menu_id`=? ORDER BY create_time DESC"
	}
	NextPageStr := "2"
	PrevPageStr := "1"
	if ctx.URLParamExists("page") {
		page := ctx.URLParam("page")
		pageInt, _ := strconv.Atoi(page)
		pageLimit := 6
		nowPageStr := strconv.Itoa((pageInt - 1) * pageLimit)
		NextPage := pageInt + 1
		PrevPage := pageInt - 1
		if PrevPage <= 1 {
			PrevPage = 1
		}
		NextPageStr = strconv.Itoa(NextPage)
		PrevPageStr = strconv.Itoa(PrevPage)

		sql = sql + " LIMIT " + nowPageStr + ",6"
	}
	ctx.ViewData("PrevPage", PrevPageStr)
	ctx.ViewData("NextPage", NextPageStr)
	articleLen := 0
	var rows *sql2.Rows
	var err error
	if ctx.URLParamExists("menuid") {
		rows, err = database.Db.Query(sql, ctx.URLParam("menuid"))
		if err != nil {
			fmt.Println("根据菜单编号查询出错，SQL原始语句：", sql)
			fmt.Println(err)
			return
		}
		menuid = ctx.URLParam("menuid")

	} else {
		rows, err = database.Db.Query(sql)
		if err != nil {
			fmt.Println("查询出错，SQL原始语句：", sql)
			fmt.Println(err)
			return
		}
	}
	for rows.Next() {
		articleLen++
		err = rows.Scan(&line.Id, &line.MenuId, &line.Title, &line.Desc, &line.Img, &line.CreateTime, &line.Hits)
		if err != nil {
			return
		}
		articles = append(articles, line)
	}
	ctx.ViewData("MenuId", menuid)
	ctx.ViewData("articles", articles)
	ctx.ViewData("articleLen", articleLen)
	ctx.ViewData("menu", model.Menus)
	_ = ctx.View("index.html")
}
